package com.enbatis.mybatisplugs.shiro;

import com.enbatis.mybatisplugs.commons.sql.Wrapper;
import com.enbatis.mybatisplugs.entity.SysUser;
import com.enbatis.mybatisplugs.entity.vo.SysUserVO;
import com.enbatis.mybatisplugs.service.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

public class UserRealm extends AuthorizingRealm {



    @Autowired
    private SysUserService sysUserService;
    /**
     * 执行授权逻辑
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection  principalCollection) {
        System.out.println("执行授权逻辑");


        String name = (String) principalCollection.getPrimaryPrincipal();
        List<SysUser> sysUserList=sysUserService.list(new Wrapper<>(new SysUser()).eq("username",name));

        SysUser dbuser=sysUserList.get(0);
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        info.addStringPermission(dbuser.getPerms());
        return info;
    }

    /**
     * 执行认证逻辑
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行认证逻辑");
        UsernamePasswordToken token=(UsernamePasswordToken)authenticationToken;
        List<SysUser> sysUserList=sysUserService.list(new Wrapper<>(new SysUser()).eq("username",token.getUsername()));
        if (CollectionUtils.isEmpty(sysUserList)){
            return  null;
        }
        SimpleAuthenticationInfo authenticationInfo=  new SimpleAuthenticationInfo(sysUserList.get(0).getUsername(),sysUserList.get(0).getPassword(),sysUserList.get(0).getUsername());
        return authenticationInfo;
    }



}